import { constants as taskConstants } from '../../../store';
import * as constants from './constants';
import { fromJS } from 'immutable';
import { getAllTaskAxios, getAllBriefConfigsAxios, getAllBriefWebApiConfigsAxios, getAllTablesAxios, getAllColumnsAxios, getAllColumnFamiliesAxios, 
  getAllFieldsAxios, getAllInputFieldAxios, getCalcTypeAxios, getCalcValueAxios, 
  buildTaskAxios, commitTaskAxios, addEleAxios, addWebApiEleAxios, addCalculatorAxios, addFilterAxios, addMergeAxios, addMergeDatabaseAxios,addReplacementAxios, 
  addOriConfigAxios, addTarConfigAxios, addTimingEleAxios,
 } from '../../../../../../api/dataCollection/taskManage'; 
import { message } from 'antd';

const getBuildTaskId = id => ({
  type: constants.BUILD_TASK,
  taskId: id,
});

export const buildTaskOperation = (values,userName) => {
  return(dispatch) => {
    let taskName = values.taskName;
    let taskType = parseInt(values.taskType);
    buildTaskAxios(taskType,taskName,userName).then((res) => {//建立任务
      if(res){
        if(res.data.ok){
          const taskId = res.data.data;
          if(values.taskType==="1"){//设定定时任务时间配置
            let repeat = parseInt(values.repeat);
            let jsonString = {};
            let timingType = parseInt(values.timingType);
            let time = undefined;
            switch(timingType){
              case 0: 
                jsonString.seconds = values.seconds;
                jsonString.minutes = values.minutes;break;
              case 1:
                time = values.daily.split(":");
                jsonString.hours = time[0];
                jsonString.minutes = time[1];break;
              case 2:
                time = values.daily.split(":");
                jsonString.hours = time[0];
                jsonString.minutes = time[1];
                jsonString.day = values.day;break;
              case 3:
                time = values.daily.split(":");
                jsonString.hours = time[0];
                jsonString.minutes = time[1];
                let date = values.month.split("-");
                jsonString.month = date[1];
                jsonString.day = date[2];
                if(values.repeat==="1"){
                  jsonString.month = 0;
                }
                break;
              default: break;
            }
            let jsonStr = JSON.stringify(jsonString);
            addTimingEleAxios(repeat,taskId,timingType,jsonStr).then((res)=>{
              if(res.data.ok){
                dispatch(getBuildTaskId(taskId));
              }
            })
          }
          else{
            dispatch(getBuildTaskId(taskId));
          }
        }
      }
    })
  }
}

const getTaskList = (tasks) => ({
  type: taskConstants.GET_TASK_LIST,
  tasks: fromJS(tasks),
});

export const getTaskListOperation = (username) => {//获取未完成任务列表
  return(dispatch) => {
    getAllTaskAxios(username).then((res) => {
      if(res){
        if(res.data.ok){
          const tasks = res.data.data;
          dispatch(getTaskList(tasks));
        }
      }
    });
  }
};

export const commitTaskOperation = (taskId,userName) => {
  return(dispatch) => {
    commitTaskAxios(taskId).then((res) => {
      if(res){
        if(res.data.ok){
          message.success("添加采集任务成功！")
          dispatch(getTaskListOperation(userName))
        }
        else{
          message.error("添加采集任务失败！")
        }
      }
    })
  }
}

export const addOriConfigOperation = (taskId,databaseId) => {
  return(dispatch) => {
    addOriConfigAxios(taskId,databaseId).then((res)=>{
      if(res){
        if(res.data.ok){
          console.log("添加源数据库配置成功！")
        }
      }
    })
  }
}

export const addTarConfigOperation = (taskId,databaseId) => {
  return(dispatch) => {
    addTarConfigAxios(taskId,databaseId).then((res)=>{
      if(res){
        if(res.data.ok){
          console.log("添加目标数据库配置成功！")
        }
      }
    })
  }
}

export const addCalculatorOperation = (taskId,data) => {
  return(dispatch) => {
    addCalculatorAxios(taskId,data).then((res)=>{
      if(res){
        if(res.data.ok){
          console.log("添加字段计算组件成功！")
        }
      }
    })
  }
}

export const addFilterOperation = (taskId,data) => {
  return(dispatch) => {
    addFilterAxios(taskId,data).then((res)=>{
      if(res){
        if(res.data.ok){
          console.log("添加字段过滤组件成功！")
        }
      }
    })
  }
}

export const addReplacementOperation = (taskId,data) => {
  return(dispatch) => {
    addReplacementAxios(taskId,data).then((res)=>{
      if(res){
        if(res.data.ok){
          console.log("添加字段替换组件成功！")
        }
      }
    })
  }
}

export const addMergeOperation = (taskId,joinTypes,keyFields1,keyFields2,databaseId,databaseType,params) => {
  return(dispatch) => {
    addMergeDatabaseAxios(taskId,databaseId).then((res)=>{
      if(res){
        if(res.data.ok){
          addEleAxios(databaseType,params).then((res) => {
            if(res){
              if(res.data.ok){
                addMergeAxios(taskId,joinTypes,keyFields1,keyFields2).then((res)=>{
                  if(res){
                    if(res.data.ok){
                      message.success("添加字段合并组件成功！");
                    }
                    else{
                      message.error("添加字段合并组件失败！");
                    }
                  }
                })
              }
            }
          })
        }
      }
    })
  }
}

export const addDatabaseEleOperation = (databaseType,params) => {//添加表输入/输出组件
  return(dispatch) => {
    addEleAxios(databaseType,params).then((res) => {
      if(res){
        if(res.data.ok){
          //此处需要对输入输出进行判断
          switch(params.databaseSymbol){
            case 0:
              message.success("添加表输入组件成功！");
              dispatch(getInputFieldOperation(params.taskId));break;
            case 1:
              message.success("添加表输出组件成功！");break;
            case 2:
              message.success("添加字段合并组件成功！");break;
            default: break;
          }
        }
        else{
          switch(params.databaseSymbol){
            case 0:
              message.error("添加表输入组件失败！");break;
            case 1:
              message.error("添加表输出组件失败！");break;
            case 2:
              message.error("添加字段合并组件失败！");break;
            default: break;
          }
        }
      }
    })
  }
}

export const addWebApiEleOperation = (taskId,databaseSymbol,databaseId,fieldNames) => {//添加表输入/输出组件
  return(dispatch) => {
    addWebApiEleAxios(taskId,databaseSymbol,databaseId,fieldNames).then((res) => {
      if(res){
        if(res.data.ok){
          message.success("添加接口输入组件成功！");
          dispatch(getInputFieldOperation(taskId));
        }
        else{
            message.error("添加接口输入组件失败！")
        }
      }
    })
  }
}

const getBriefConfig = briefConfig => ({
  type: constants.GET_BRIEF_CONFIG,
  briefConfig: fromJS(briefConfig),
});

export const getBriefConfigOperation = (userName) => {//获取除webapi外的所有连接配置
  return(dispatch) => {
    getAllBriefConfigsAxios(userName).then((res) => {
      if(res){
        if(res.data.ok){
          const briefConfig = res.data.data;
          console.log("数据源",briefConfig);
          dispatch(getBriefConfig(briefConfig));
        }
      }
    })
  }
}

const getBriefWebConfig = briefWebConfig => ({
  type: constants.GET_BRIEF_WEB_CONFIG,
  briefWebConfig: fromJS(briefWebConfig),
});

export const getBriefWebConfigOperation = (userName) => {//获取webapi的所有连接配置
  return(dispatch) => {
    getAllBriefWebApiConfigsAxios(userName).then((res) => {
      if(res){
        if(res.data.ok){
          const briefWebConfig = res.data.data;
          console.log("webapi数据源",briefWebConfig);
          dispatch(getBriefWebConfig(briefWebConfig));
        }
      }
    })
  }
}

const getOriginTable = table => ({
  type: constants.GET_ORIGIN_TABLE,
  table: fromJS(table),
});

export const getOriginTableOperation = (dataType,params) => {//根据所选的源数据库获取表列表
  return(dispatch) => {
    getAllTablesAxios(dataType,params).then((res) => {
      if(res){
        if(res.data.ok){
          const table = res.data.data;
          dispatch(getOriginTable(table));
        }
      }
    })
  }
}

export const clearOriginTableOperation = () => {
  return(dispatch) => {
    dispatch(getOriginTable([]));
  }
}

const getTargetTable = table => ({
  type: constants.GET_TARGET_TABLE,
  table: fromJS(table),
});

export const getTargetTableOperation = (dataType,params) => {//根据所选的目标数据库获取表列表
  return(dispatch) => {
    getAllTablesAxios(dataType,params).then((res) => {
      if(res){
        if(res.data.ok){
          const table = res.data.data;
          dispatch(getTargetTable(table));
        }
      }
    })
  }
}

export const clearTargetTableOperation = () => {
  return(dispatch) => {
    dispatch(getTargetTable([]));
  }
}

const getColumns = column => ({
  type: constants.GET_COLUMNS,
  column: fromJS(column),
});

export const getColumnsOperation = (dataType,params) => {//获取某张表/hbase列族的所有列
  return(dispatch) => {
    getAllColumnsAxios(dataType,params).then((res) => {
      if(res){
        if(res.data.ok){
          const column = res.data.data;
          dispatch(getColumns(column));
        }
      }
    })
  }
}

const getColumnFamily = columnFamily => ({
  type: constants.GET_COLUMN_FAMILY,
  columnFamily: fromJS(columnFamily),
});

export const getColumnFamilyOperation = (id,database) => {//获取hbase表的所有列族
  return(dispatch) => {
    getAllColumnFamiliesAxios(id,database).then((res) => {
      if(res){
        if(res.data.ok){
          const columnFamily = res.data.data;
          dispatch(getColumnFamily(columnFamily));
        }
      }
    })
  }
}

const clearField = () => ({
  type: constants.CLEAR_FIELD,
  column: fromJS([]),
  columnFamily: fromJS([]),
  field: fromJS([]),
})

export const clearFieldOperation = () => {
  return(dispatch) => {
    dispatch(clearField());
  }
}

const getFields = (field) => ({
  type: constants.GET_FIELD,
  field: fromJS(field),
})

export const getFieldsOperation = (databaseId) => {//获取api接口的字段配置
  return(dispatch) => {
    getAllFieldsAxios(databaseId).then((res) => {
      if(res){
        if(res.data.ok){
          const field = res.data.data;
          dispatch(getFields(field));
        }
      }
    })
  }
}

const getInputField = (inputField,outputField) => ({
  type: constants.GET_INPUT_FIELD,
  inputField: fromJS(inputField),
  outputField: fromJS(outputField)
})

export const getInputFieldOperation = (taskId) => {//获取该任务源数据库以及字段配置
  return(dispatch) => {
    getAllInputFieldAxios(taskId).then((res) => {
      if(res){
        if(res.data.ok){
          const inputField = res.data.data;
          const outputField = inputField.map(item=>item.fieldName);
          dispatch(getInputField(inputField,outputField));
        }
      }
    })
  }
}

const changeOutputField = (outputField) => ({
  type: constants.GET_OUTPUT_FIELD,
  outputField: fromJS(outputField)
})

export const changeOutputFieldOperation = (outputField) => {//获取该任务源数据库以及字段配置
  return(dispatch) => {
    dispatch(changeOutputField(outputField));
  }
}

const getCalcType = (calcType) => ({
  type: constants.GET_CALC_TYPE,
  calcType: fromJS(calcType),
})

export const getCalcTypeOperation = () =>  {
  return (dispatch) => {
    getCalcTypeAxios().then((res) => {
      if(res.data.ok) {
        let responseData = res.data.data;
        let keyArr = Object.keys(responseData);
        let calcType = [];
        keyArr.map((item, index) => {
          let obj = {
            key: item,
            text: item,
            value: responseData[item]
          }
          calcType.push(obj)
          return calcType;
        })
        dispatch(getCalcType(calcType))
      }
    })
  } 
}

const getCalcValue = (calcValueType) => ({
  type: constants.GET_CALC_VALUE_TYPE,
  calcValueType: fromJS(calcValueType),
})

export const getCalcValueOperation = () =>  {
  return (dispatch) => {
    getCalcValueAxios().then((res) => {
      if(res.data.ok) {
        let responseData = res.data.data;
        let keyArr = Object.keys(responseData);
        let calcValueType = [];
        keyArr.map((item, index) => {
          let obj = {
            key: item,
            text: item,
            value: responseData[item]
          }
          calcValueType.push(obj);
          return calcValueType;
        })
        dispatch(getCalcValue(calcValueType))
      }
    })
  } 
}

const clearMergeField = () => ({
  type: constants.CLEAR_MERGE_FIELD,
  mColumnFamily: fromJS([]),
  mField: fromJS([]),
})

export const clearMergeFieldOperation = () => {
  return(dispatch) => {
    dispatch(clearMergeField());
  }
}

const getMergeTable = mTable => ({
  type: constants.GET_MERGE_TABLE,
  mTable: fromJS(mTable),
});

export const getMergeTableOperation = (dataType,params) => {//根据所选的目标数据库获取表列表
  return(dispatch) => {
    getAllTablesAxios(dataType,params).then((res) => {
      if(res){
        if(res.data.ok){
          const mTable = res.data.data;
          dispatch(getMergeTable(mTable));
        }
      }
    })
  }
}

const getMergeField = mField => ({
  type: constants.GET_MERGE_FIELD,
  mField: fromJS(mField),
});

export const getMergeFieldOperation = (dataType,params) => {//获取某张表/hbase列族的所有列
  return(dispatch) => {
    getAllColumnsAxios(dataType,params).then((res) => {
      if(res){
        if(res.data.ok){
          const mField = res.data.data;
          dispatch(getMergeField(mField));
        }
      }
    })
  }
}

const getMergeColumnFamily = mColumnFamily => ({
  type: constants.GET_COLUMN_FAMILY,
  mColumnFamily: fromJS(mColumnFamily),
});

export const getMergeColumnFamilyOperation = (id,database) => {//获取hbase表的所有列族
  return(dispatch) => {
    getAllColumnFamiliesAxios(id,database).then((res) => {
      if(res){
        if(res.data.ok){
          const mColumnFamily = res.data.data;
          dispatch(getMergeColumnFamily(mColumnFamily));
        }
      }
    })
  }
}